package com.example.tranport.client;

import com.example.tranport.client.destination.ClientDestinationService;
import com.example.tranport.client.destination.ClientDestinationServiceImpl;
import com.example.tranport.client.message.ClientMessageService;
import com.example.tranport.client.message.ClientMessageServiceImpl;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.DisposableBean;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;

public class ClientFactory implements InitializingBean, ApplicationContextAware, DisposableBean {

    private ClientTransPortImpl clientTransPort;

    private ApplicationContext applicationContext;

    private String host;

    private int port;

    private ClientMessageService clientMessageService;

    private ClientDestinationService clientDestinationService;

    @Override
    public void afterPropertiesSet() throws Exception {
        if (this.clientDestinationService == null) {
            this.clientDestinationService = new ClientDestinationServiceImpl(applicationContext);
        }
        if (this.clientMessageService == null){
            this.clientMessageService = new ClientMessageServiceImpl(this);
        }
        this.clientTransPort = new ClientTransPortImpl(this);
        this.clientTransPort.start();
    }

    @Override
    public void destroy() throws Exception {
        this.clientTransPort.stop();
    }

    public ClientTransPortImpl getClientTransPort() {
        return clientTransPort;
    }

    public void setClientTransPort(ClientTransPortImpl clientTransPort) {
        this.clientTransPort = clientTransPort;
    }

    public String getHost() {
        return host;
    }

    public void setHost(String host) {
        this.host = host;
    }

    public int getPort() {
        return port;
    }

    public void setPort(int port) {
        this.port = port;
    }

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        this.applicationContext = applicationContext;
    }

    public ClientDestinationService getClientDestinationService() {
        return clientDestinationService;
    }

    public void setClientDestinationService(ClientDestinationService clientDestinationService) {
        this.clientDestinationService = clientDestinationService;
    }

    public ApplicationContext getApplicationContext() {
        return applicationContext;
    }

    public ClientMessageService getClientMessageService() {
        return clientMessageService;
    }

    public void setClientMessageService(ClientMessageService clientMessageService) {
        this.clientMessageService = clientMessageService;
    }
}
